<!-- src/views/SysConfig.vue -->
<template>
  <div class="sys-config-container">
    <h2>系统配置管理</h2>

    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleRefreshCache">
        <el-icon><Refresh /></el-icon> 刷新配置缓存
      </el-button>
      <el-button type="success" @click="showHistoryDialog = true">
        <el-icon><Clock /></el-icon> 查看配置历史
      </el-button>
    </div>

    <!-- 配置列表 -->
    <el-card class="config-card" style="margin-top: 15px;">
      <el-table
          :data="configList"
          border
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="configKey" label="配置键" />
        <el-table-column prop="configValue" label="配置值" />
        <el-table-column prop="configDesc" label="配置描述" />

        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑配置弹窗 -->
    <el-dialog
        :title="isEdit ? '编辑配置' : '新增配置'"
        v-model="dialogVisible"
        width="600px"
    >
      <el-form
          :model="formData"
          :rules="formRules"
          ref="configForm"
          label-width="120px"
      >
        <el-form-item label="配置键" prop="configKey" v-if="!isEdit">
          <el-input v-model="formData.configKey" placeholder="请输入配置键" />
        </el-form-item>
        <el-form-item label="配置名称" prop="configName">
          <el-input v-model="formData.configName" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="配置值" prop="configValue">
          <el-input
              v-model="formData.configValue"
              placeholder="请输入配置值"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="formData.remark"
              placeholder="请输入备注信息"
              type="textarea"
              :rows="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 配置历史弹窗 -->
    <el-dialog
        title="配置变更历史"
        v-model="showHistoryDialog"
        width="800px"
    >
      <el-form
          :inline="true"
          :model="historyQuery"
          class="history-search-form"
      >
        <el-form-item label="配置ID">
          <el-input v-model="historyQuery.configId" placeholder="请输入配置ID" clearable />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
              v-model="historyTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getConfigHistory">查询</el-button>
          <el-button @click="resetHistoryQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
          :data="historyList"
          border
          style="width: 100%; margin-top: 10px;"
          v-loading="historyLoading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="configId" label="配置ID" width="100" />
        <el-table-column prop="configKey" label="配置键" />
        <el-table-column prop="oldValue" label="旧值" />
        <el-table-column prop="newValue" label="新值" />
        <el-table-column prop="operUser" label="操作人" width="120" />
        <el-table-column prop="operTime" label="操作时间" width="180" />
        <el-table-column prop="remark" label="变更说明" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { SysConfigApi } from '@/api/sysConfig.js';
import { Refresh, Clock } from '@element-plus/icons-vue';

// 状态变量
const loading = ref(false);
const historyLoading = ref(false);
const configList = ref([]);
const historyList = ref([]);
const dialogVisible = ref(false);
const showHistoryDialog = ref(false);
const isEdit = ref(false);

// 表单数据
const formData = reactive({
  id: undefined,
  configKey: '',
  configValue: '',
  configName: '',
  remark: ''
});

// 历史查询参数
const historyQuery = reactive({
  configId: '',
  startTime: '',
  endTime: ''
});
const historyTimeRange = ref([]);

// 表单验证规则
const formRules = {
  configKey: [
    { required: true, message: '请输入配置键', trigger: 'blur' }
  ],
  configValue: [
    { required: true, message: '请输入配置值', trigger: 'blur' }
  ],
  configName: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ]
};

// 表单引用
const configForm = ref(null);

// 加载配置列表
const loadConfigList = async () => {
  try {
    loading.value = true;
    const res = await SysConfigApi.getAllConfigs();
    configList.value = res.data || [];
  } catch (error) {
    console.error('加载配置列表失败:', error);
    ElMessage.error(error.message || '加载配置列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取配置历史
const getConfigHistory = async () => {
  try {
    historyLoading.value = true;
    const params = { ...historyQuery };
    if (historyTimeRange.value && historyTimeRange.value.length === 2) {
      params.startTime = historyTimeRange.value[0];
      params.endTime = historyTimeRange.value[1];
    }
    const res = await SysConfigApi.getConfigHistory(params);
    historyList.value = res.data || [];
  } catch (error) {
    console.error('获取配置历史失败:', error);
    ElMessage.error(error.message || '获取配置历史失败');
  } finally {
    historyLoading.value = false;
  }
};

// 编辑配置
const handleEdit = (row) => {
  isEdit.value = true;
  Object.assign(formData, { ...row });
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await configForm.value.validate();
    await SysConfigApi.updateConfig(formData);
    ElMessage.success('配置更新成功');
    dialogVisible.value = false;
    loadConfigList();
  } catch (error) {
    console.error('配置提交失败:', error);
    ElMessage.error(error.message || '配置提交失败');
  }
};

// 刷新缓存
const handleRefreshCache = async () => {
  try {
    await SysConfigApi.refreshCache();
    ElMessage.success('配置缓存刷新成功');
  } catch (error) {
    console.error('刷新缓存失败:', error);
    ElMessage.error(error.message || '刷新缓存失败');
  }
};

// 重置历史查询
const resetHistoryQuery = () => {
  Object.assign(historyQuery, {
    configId: '',
    startTime: '',
    endTime: ''
  });
  historyTimeRange.value = [];
  getConfigHistory();
};

// 监听时间范围变化
watch(historyTimeRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    historyQuery.startTime = newVal[0];
    historyQuery.endTime = newVal[1];
  } else {
    historyQuery.startTime = '';
    historyQuery.endTime = '';
  }
});

// 页面挂载时加载数据
onMounted(() => {
  loadConfigList();
});
</script>

<style scoped>
.sys-config-container {
  padding: 20px;
}

.action-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.history-search-form {
  margin-bottom: 15px;
}
</style>